from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User


class Category(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('blog:category', kwargs={'pk': self.pk})


class Tag(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name


class Post(models.Model):
    title = models.CharField(max_length=70)
    body = models.TextField()
    created_time = models.DateTimeField()
    modified_time = models.DateTimeField()
    # 文章摘要，可以为空白
    excerpt = models.CharField(max_length=200, blank=True)
    # 分类
    category = models.ForeignKey(Category)
    # 标签
    tags = models.ManyToManyField(Tag, blank=True)
    # 作者
    author = models.ForeignKey(User)

    class Meta:
        ordering = ['-created_time']

    def __str__(self):
        return self.title

    # 反向解析获取路径
    def get_absolute_url(self):
        return reverse('blog:detail', kwargs={'pk': self.pk})
